<script setup lang="ts">
import configs from '@/config/index'
import storage from '@/utils/storage'
import { getBaseSite } from '@/api/common'

// https://github.com/vueuse/head
// you can use this to manipulate the document head in any components,
// they will be rendered correctly in the html results with vite-ssg
useHead({
  title: configs.title,
  meta: [
    {
      name: 'description',
      content: configs.meta.description
    },
    {
      name: 'keywords',
      content: configs.meta.keywords
    }
  ],
  // link: [
  //   {
  //     rel: 'icon',
  //     type: 'image/svg+xml',
  //     href: () => (preferredDark.value ? '/favicon-dark.svg' : '/favicon.svg')
  //   }
  // ]
})

// 获取基本站点信息
function getSite() {
  // 获取基本站点信息
  getBaseSite().then((res) => {
    if (res.data.success && res.data.result.settingValue) {
      const data = JSON.parse(res.data.result.settingValue)
      // 过期时间
      const expirationTime = new Date().setHours(new Date().getHours() + 1)
      // 存放过期时间
      storage.setSitelogoExpirationTime(expirationTime)
      // 存放信息
      storage.setSiteName(data.siteName)
      storage.setLogoImg(data.buyerSideLogo)
      storage.setSiteIcon(data.buyerSideIcon)
      window.document.title = data.siteName
      // 动态获取icon
      // const link = document.querySelector("link[rel*='icon']") || (document.createElement('link') as any)
      // link.type = 'image/x-icon'
      // link.href = data.buyerSideIcon
      // link.rel = 'shortcut icon'
      // document.getElementsByTagName('head')[0].appendChild(link)
    }
  })
}
function init() {
  if (!storage.getSiteName() || !storage.getLogoImg() || !storage.getSitelogoExpirationTime()) {
    getSite()
  } else {
    // 如果缓存过期，则获取最新的信息
    if (Number(new Date()) > Number(storage.getSitelogoExpirationTime())) {
      getSite()
    } else {
      window.document.title = JSON.parse(JSON.stringify(storage.getSiteName()))
      // 动态获取icon
      // const link = document.querySelector("link[rel*='icon']") || (document.createElement('link') as any)
      // link.type = 'image/x-icon'
      // link.href = storage.getSiteIcon()
      // link.rel = 'shortcut icon'
      // document.getElementsByTagName('head')[0].appendChild(link)
    }
  }
}

onMounted(() => {
  // init()
})
</script>

<template>
  <RouterView />
</template>
